package com.songcha.sakura.ui.view.video

import android.app.Activity
import android.content.Context
import android.graphics.Canvas
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.*
import com.songcha.library_common.ui.view.loading.FlowerLoadingView
import com.songcha.library_common.util.ScreenUtil
import com.songcha.sakura.R
import com.songcha.sakura.ui.view.IOnSeekChangeListener
import com.songcha.sakura.ui.view.VideoSeekBar
//import com.songcha.sakura.ui.view.loading.FlowerLoadingView
import com.songcha.sakura.util.*
import com.songcha.library_common.util.TimeUtil
import kotlin.math.absoluteValue

interface IOnVideoListener{
    fun onPrepared()
    fun onPlay()
    fun onPause()
    fun onCompletion()

}

enum class VideoState{
    IDLE,
    PLAYING,
    PAUSE,
}

class VideoController :FrameLayout, IOnSeekChangeListener,View.OnClickListener,IOnVideoListener {
    private var mPlayer:CustomVideoPlayer?=null
    private lateinit var mSeekBar:VideoSeekBar
    private var mIsShowView=true
    private lateinit var mView:View
    private var lastX=0f
    private var lastY=0f
    //private lateinit var mContext:Context
    private lateinit var mTvProgressCurrent:TextView//当前进度
    private lateinit var mTvProgressTotal:TextView//总进度
    //private val SEEK_RATIO=0.02
    private lateinit var mBtnPlay:ImageButton
    private lateinit var mFLVLoading: FlowerLoadingView
    private lateinit var mIvBack: ImageView
    private lateinit var mTvTitle:TextView
    private lateinit var mTvProgressTip:TextView
    private var mAutoHideThread:Thread?=null
    private var mSeekRatio=16f
    private var mSw=0
    private var mSeekOffset=0
    private var mIsSeek=false
    private var mState=VideoState.IDLE
    private var mLastClickTime=0L
    private val DOUBLE_CLICK_INTERVAL=300L
    private var  mIsDoubleClickPause=false


    constructor(context: Context) : super(context) {
        initView(context,null)
    }

    constructor(context: Context, attrs: AttributeSet):this(context,attrs,0){

    }

    constructor(context: Context, attrs: AttributeSet, defStyle:Int):this(context,attrs,defStyle,0){

    }

    constructor(context: Context, attrs: AttributeSet, defStyle:Int, defRes:Int):super(context,attrs,defStyle,defRes){
        initView(context,attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?){
        //mContext=context

        isClickable=true


        mView=LayoutInflater.from(context).inflate(R.layout.view_video_controller,this,false)

        mSeekBar=mView.findViewById(R.id.vsb)
        mSeekBar.setOnSeekListener(this)

        mTvProgressCurrent=mView.findViewById(R.id.tv_progress_current)
        mTvProgressTotal=mView.findViewById(R.id.tv_progress_total)
        mBtnPlay=mView.findViewById(R.id.ib_play)
        mFLVLoading=mView.findViewById(R.id.flv_loading)
        mIvBack=mView.findViewById(R.id.iv_back)
        mTvTitle=mView.findViewById(R.id.tv_title)
        mTvProgressTip=mView.findViewById(R.id.tv_progress_tip)

        mBtnPlay.visibility=View.GONE
        mFLVLoading.visibility=View.VISIBLE

        mBtnPlay.setOnClickListener(this)
        mIvBack.setOnClickListener(this)

        addView(mView)

        refreshView()

        mSw= ScreenUtil.getScreenWidth(context)

        mAutoHideThread=buildAutoHideThread()
        mAutoHideThread?.start()

        mState=VideoState.IDLE



    }

   /* private val mAutoHideThread=Thread{
        Thread.sleep(5000)
        if(mPlayer?.getMediaPlayer()?.isPlaying == true &&  mIsShowView){
            Handler(Looper.getMainLooper()).post {
                mIsShowView=false
                refreshView()
            }
        }
    }*/

    fun setTitle(title:String){
        mTvTitle.text=title
    }

    fun buildAutoHideThread():Thread{
        return Thread{
            try {
                Thread.sleep(5000)
                if(mPlayer?.getMediaPlayer()?.isPlaying == true &&  mIsShowView){
                    Handler(Looper.getMainLooper()).post {
                        mIsShowView=false
                        refreshView()
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }


    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if(event!=null){

            if(mAutoHideThread?.isAlive==true){
                mAutoHideThread?.interrupt()
            }

            if(event.action==MotionEvent.ACTION_DOWN){

                if(mLastClickTime>0 && System.currentTimeMillis()-mLastClickTime<=DOUBLE_CLICK_INTERVAL){
                    mIsDoubleClickPause=true
                    if(mState==VideoState.PLAYING){
                        mIsShowView=true
                        onPause()
                    }else{
                        onPlay()
                    }
                    mLastClickTime=0L
                }else{
                    mIsDoubleClickPause=false
                    mLastClickTime=System.currentTimeMillis()

                    mTvProgressTip.visibility=View.INVISIBLE
                    lastX=event.x
                    lastY=event.y
                }

            }
            else if(event.action==MotionEvent.ACTION_MOVE){

                val deltaX=event.x-lastX
                val deltaY=event.y-lastY
                if(mIsShowView && deltaX.absoluteValue>deltaY.absoluteValue){

                    mTvProgressTip.visibility=View.VISIBLE

                    mSeekOffset=(deltaX/mSeekRatio).toInt()

                    mIsSeek=true

                    val curPosition=(mPlayer?.getMediaPlayer()?.currentPosition?:0)+mSeekOffset*1000
                    if(curPosition>=0 && curPosition<=mPlayer?.getMediaPlayer()?.duration?:0){
                        mTvProgressTip.text=TimeUtil.getTimeByMillSecond(curPosition)+"/"+TimeUtil.getTimeByMillSecond(mPlayer?.getMediaPlayer()?.duration)
                    }


                }else{
                    mIsSeek=false
                }


            }
            else if(event.action==MotionEvent.ACTION_UP){

                //val deltaX=event.x-lastX
                //val deltaY=event.y-lastY
                if(mIsDoubleClickPause) return super.onTouchEvent(event)


                if(mIsSeek){
                    //val currentPercent=getCurrentPercent()
                    //val deltaPercent=((deltaX.absoluteValue*1.0f/sw)*100).toInt()
                    //LogUtil.log(deltaX,(deltaX/mSeekRatio).toInt())
                    seekToOffset(mSeekOffset)
                    mIsSeek=false

                 /*   var seekPercent=0
                    if(deltaX>0){
                        seekPercent=currentPercent+deltaPercent
                    }else{
                        seekPercent=currentPercent-deltaPercent
                    }*/
                    //seekTo(seekPercent)

                    mIsShowView=!mIsShowView

                    refreshView(2000)
                }else{
                    mIsShowView=!mIsShowView
                    refreshView()

                }

                autoHide()

            }
        }
        return super.onTouchEvent(event)
    }

    private fun autoHide(){
        //无操作自动隐藏
        if(mPlayer?.getMediaPlayer()?.isPlaying == true &&  mIsShowView && (mAutoHideThread==null || mAutoHideThread?.isAlive==false)){
            mAutoHideThread=buildAutoHideThread()
            mAutoHideThread?.start()
        }
    }


    private fun refreshView(delay:Long=0){
        fun refresh(){

            if(mIsShowView){
                mView.visibility=View.VISIBLE
            }else{
                mView.visibility=View.GONE
            }

            if(mState==VideoState.PLAYING){
                mBtnPlay.setImageResource(R.mipmap.icon_pause)
            }else{
                mBtnPlay.setImageResource(R.mipmap.icon_play)
            }

            mTvProgressCurrent.text= TimeUtil.getTimeByMillSecond(mPlayer?.getMediaPlayer()?.currentPosition)
            mTvProgressTotal.text=TimeUtil.getTimeByMillSecond(mPlayer?.getMediaPlayer()?.duration)


        }

        if(delay>0){
            Handler(Looper.getMainLooper()).postDelayed({
                refresh()
            },delay)
        }else{
            refresh()
        }

    }


    fun setProgress(progress:Int){
        mSeekBar.setProgress(progress)
        refreshView()
    }


    fun setVideoPlayer(cvp:CustomVideoPlayer){
        this.mPlayer=cvp
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
    }

    override fun onSeek(percent: Int) {
        seekToPercent(percent)
    }

    /*private fun getCurrentPercent():Int{
        val duration=mPlayer?.getMediaPlayer()?.duration
        val currentPosition=mPlayer?.getMediaPlayer()?.currentPosition
        if(duration==null || currentPosition==null) return 0
        return ((currentPosition*1.0f)/duration*100).toInt()
    }*/

    /*private fun seekTo(percent: Int){
        if(percent<0 || percent>100) return
        val duration=mPlayer?.getMediaPlayer()?.duration
        if(duration!=null && duration >0){
            mPlayer?.getMediaPlayer()?.seekTo(duration * percent/100)
        }

    }*/

    /*private fun seekTo(position: Int){
        if(position<0) return
        val duration=mPlayer?.getMediaPlayer()?.duration
        if(duration!=null && duration >0){
            mPlayer?.getMediaPlayer()?.seekTo(position*1000)
        }
    }*/

    private fun seekToOffset(offset: Int){
        val currentPosition=mPlayer?.getMediaPlayer()?.currentPosition
        if(currentPosition!=null && currentPosition >0 && currentPosition+offset>=0){
            mPlayer?.getMediaPlayer()?.seekTo(currentPosition+offset*1000)
            refreshView()
        }
    }

    private fun seekToPercent(percent: Int){
        if(percent<0 || percent>100) return
        val duration=mPlayer?.getMediaPlayer()?.duration
        if(duration!=null && duration >0){
            mPlayer?.getMediaPlayer()?.seekTo(duration * percent/100)
            refreshView()
        }

    }


    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.ib_play->{
                if(mState==VideoState.IDLE) return
                if(mIsShowView && mPlayer?.getMediaPlayer()?.isPlaying == true){
                    //mPlayer?.getMediaPlayer()?.pause()
                    //mBtnPlay.setImageResource(R.mipmap.icon_play)
                    onPause()
                }else{
                    //mPlayer?.getMediaPlayer()?.start()
                    //mBtnPlay.setImageResource(R.mipmap.icon_pause)
                    onPlay()
                    autoHide()
                }
            }
            R.id.iv_back->{
                //savePlayHistoryProgress()
                //(mContext as Activity).finish()
                (context as Activity).finish()
            }
        }
    }


    //读取播放进度
    fun readPlayHistoryProgress(){

        val bean=VideoUtil.readPlayHistoryProgress(mPlayer?.getName()?:"")
        if(bean!=null){
            if(bean.position>0)
                mPlayer?.getMediaPlayer()?.seekTo(bean.position)
        }
    }

    //保存播放进度
    fun savePlayHistoryProgress(){
        VideoUtil.savePlayHistoryProgress(mPlayer?.getName()?:"",mPlayer?.getMediaPlayer()?.currentPosition?:0,mPlayer?.getMediaPlayer()?.duration?:0)
    }

    override fun onPrepared() {
        mState=VideoState.PLAYING
        mFLVLoading.visibility=View.GONE
        mBtnPlay.visibility=View.VISIBLE
        refreshView()
    }

    override fun onPlay() {
        mState=VideoState.PLAYING
        mPlayer?.getMediaPlayer()?.start()
        mBtnPlay.setImageResource(R.mipmap.icon_pause)
        mIsDoubleClickPause=false
        refreshView()
    }

    override fun onPause() {
        mState=VideoState.PAUSE
        mPlayer?.getMediaPlayer()?.pause()
        mBtnPlay.setImageResource(R.mipmap.icon_play)
        refreshView()
        //savePlayHistoryProgress()
    }

    override fun onCompletion() {
        mPlayer?.getMediaPlayer()?.seekTo(mPlayer?.getMediaPlayer()?.duration?:0)
        mIsShowView=true
        onPause()
    }


}